package com.lc.stock.module.filtrate.filter;

import cn.hutool.core.collection.CollUtil;
import com.lc.stock.module.filtrate.filter.bean.FilterResult;
import org.springframework.context.ApplicationContext;

import java.util.*;

/**
 * @author lichen
 * @description 股票筛选链
 * @menu
 * @date 2023/2/6 16:11
 */
public class FiltrateStockFilterChain {

    //过滤器集合
    private Collection<FiltrateStockFilter> filters;

    public FiltrateStockFilterChain(ApplicationContext applicationContext){
        Map<String, FiltrateStockFilter> beansOfType = applicationContext.getBeansOfType(FiltrateStockFilter.class);
        filters = beansOfType.values();
    }

    public FiltrateStockFilterChain(ApplicationContext applicationContext, List<String> filterNames){
        Map<String, FiltrateStockFilter> beansOfType = applicationContext.getBeansOfType(FiltrateStockFilter.class);
        Collection<FiltrateStockFilter> allFilters = beansOfType.values();
        for (FiltrateStockFilter filter : allFilters) {
            if(filterNames.contains(filter.getFilterName())){
                filters.add(filter);
            }
        }
    }

    /**
     * 执行筛选
     * @param stockCode
     * @return
     */
    public FilterResult filter(String stockCode){
        FilterResult filterResult = new FilterResult();
        filterResult.setStockCode(stockCode);
        filterResult.setIfSelect(1);

        int doFilterSize = 0;
        //执行过滤，选股
        Iterator<FiltrateStockFilter> iterator = filters.iterator();
        while(iterator.hasNext()){
            if(!iterator.next().doFilter(stockCode)){
                break;
            }
            doFilterSize ++;
        }

        if(doFilterSize < filters.size()){
            //股票不符合条件，记录选股失败的信息
            FiltrateStockFilter filtrateStockFilter = CollUtil.get(filters, doFilterSize);
            filterResult.setMessage(filtrateStockFilter.getErrorMsg());
            filterResult.setIfSelect(0);
        }
        return filterResult;
    }

}
